/**
 * @Author: 陈瑞鹏
 * @Date:   2021-11-08 19:19:24
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2023-01-11 09:47:11
 */
import { INotification } from "../pureMvc/Interfaces";
import { MediatorGameLayer } from "./MediatorGameLayer";
import { Notifier } from "../pureMvc/patterns/observer/Notifier";

import { ResManager } from "../manager/ResManager";
import { SceneManager } from "../manager/SceneManager";
import { PureMVCEvents } from "./PureMVCEvents";

const { ccclass, property } = cc._decorator

export enum LAYER_Z_INDEX {

    DEFAULT = 0,
    GUI_LAYER = 50,             //用户界面ui层（菜单栏\主界面头像栏 等）
    EFFECT_LAYER = 101,         //特效层 （战斗全屏特效 等）
    PUSH_LAYER_INDEX_1 = 201,   //弹出层
    PUSH_LAYER_INDEX_2 = 202,   //弹出层
    PUSH_LAYER_INDEX_3 = 203,   //弹出层
    PUSH_LAYER_INDEX_4 = 204,   //弹出层
    FIX_LAYER = 301,            //固定层
    UI_BATTLE_END = 401,        //结算界面
    UI_DIALOG = 501,            //对话框层
    MASK_LAYER = 601,		        //顶级弹出层 （断线重连\大礼包投放 等）
    UI_LOADING_LAYER = 701,		        //顶级弹出层 （断线重连\大礼包投放 等）
}

@ccclass

export default class BaseGameLayer extends cc.Component {

    @property({ type: cc.Enum(LAYER_Z_INDEX) })
    public zIndex: LAYER_Z_INDEX = LAYER_Z_INDEX.DEFAULT;

    @property
    public isRemoveSameLayer: boolean = true;

    @property
    public isReleaseResOnRemoveLayer: boolean = false;

    @property({ tooltip: "按钮是否点击音效" })
    private isBtnSound: boolean = true;

    @property({ tooltip: "x方向弹出" })
    disX: number = 100;

    @property({ tooltip: "y方向弹出" })
    disY: number = 100;

    @property({ tooltip: "延迟时间" })
    delay: number = 0.2;

    @property({ tooltip: "界面是否弹出" })
    private isEject: boolean = false;

    private btnArr: Array<cc.Button> = null;

    protected mediator: MediatorGameLayer = null;
    protected m_bIsRunning: boolean = false;
    protected customData: any = null;
    protected _nodePrefab: cc.Prefab = null;
    protected spritList: Array<cc.Sprite> = null;
    protected _isTouchEnable: boolean = false;

    onEnable() {

        this.mediator = this.mediator || new MediatorGameLayer(this.getClassName(), this);
        this.mediator.registerMediator();
    }


    getClassName() {
        return this.node.name;
    }

    /************************************Layer公用方法START**********************************************/

    public handleNotification(notification: INotification): void {

    }

    public sendNotification(name: string, body: any = null, type: string = null): void {
        if (this.mediator && (<Notifier>this.mediator).multitonKey != null)
            this.mediator.sendNotification(name, body, type);
    }

    public listNotificationInterests(): Array<string> {
        return [];
    }
    public getDisplayView(): cc.Node {
        return this.node;
    }
    public setIsRunning(isRunning: boolean): void {
        this.m_bIsRunning = isRunning;
    }
    public getIsRunning(): boolean {
        return this.m_bIsRunning;
    }

    protected getIsTouchEnable(): boolean {
        return this._isTouchEnable;
    }

    public onAddToStage(): void {
        let that: BaseGameLayer = this;
        cc.tween(this.node)
            .sequence(cc.delayTime(0.3), cc.callFunc(function () {
                that._isTouchEnable = true;
            }));
        this.mediator = this.mediator || new MediatorGameLayer(this.getClassName(), this);
        this.mediator.registerMediator();

        this.sendNotification(PureMVCEvents.ON_LAYER_ADD_TO_STAGE);

        if (this.isBtnSound) {
            this.btnArr = this.node.getComponentsInChildren(cc.Button);

            if (this.btnArr && this.btnArr.length > 0) {
                for (let i = 0, count = this.btnArr.length; i < count; i++) {
                    this.btnArr[i].node.on('click', this.btn_onEvent, this);
                    // Utils.addButtonEvent(this.btnArr[i],'btn_onEvent',this.btnArr[i].node,this.getClassName());
                }
            }
        }
        else {
            this.btnArr = null;
        }

        /**
         * 弹出动画
         */
        if (this.isEject) {
            this.node.x = -this.disX;
            this.node.y = -this.disY;
            // console.log(this.node.x, this.node.y);
            cc.tween(this.node)
                .to(0.5, { x: 0, y: 0 }, { easing: "quintOut" })
                .start();
        }

    }

    private btn_onEvent() {
       
    }

    public onRemoveFromStage(): void {
        this.sendNotification(PureMVCEvents.ON_LAYER_REMOVE_FROME_STAGE)
        //this.DestroyLayerRes();
        this._isTouchEnable = false;
        let that = this;
        /**
         * 弹出动画
         */
        if (this.isEject) {
            // console.log(this.node.x, this.node.y);
            cc.tween(this.node)
                .to(0.5, { x: -this.disX, y: -this.disY }, { easing: "quintOut" })
                .call(() => {
                    if (that.getDisplayView().parent) {
                        that.getDisplayView().parent.removeChild(that.getDisplayView(), false);
                    }
                })
                .start();
        } else {
            if (that.getDisplayView().parent) {
                that.getDisplayView().parent.removeChild(that.getDisplayView(), false);
            }
        }
    }

    public onDisable(): void {
        if (this.mediator)
            this.mediator.removeMediator();

        if (this.btnArr && this.btnArr.length > 0) {
            for (let i = 0, count = this.btnArr.length; i < count; i++) {
                this.btnArr[i].node.off('click', this.btn_onEvent, this);
            }
        }
    }

    public setPrefab(p: cc.Prefab): void {
        this._nodePrefab = p;
    }

    public getPrefab(): any {
        return this._nodePrefab;
    }

    public setPushLayerCustomData(obj: any): void {

        this.customData = obj;
        if (this.customData)
            this.onDataChanged();
    }
    public getPushLayerCustomData(): any {
        return this.customData;
    }
    public getLayerName(): string {
        let view = this.getDisplayView()
        if (view) {
            return view.name
        }
        return "";
    }

    public getLayerLocalIndex(): LAYER_Z_INDEX {
        return this.zIndex;
    }

    public RecoverAnima() {
        //恢复帧动画
        let frameAnima = this.node.getComponentsInChildren(cc.Animation)
        if (frameAnima.length > 0) {
            for (let i = 0; i < frameAnima.length; i++) {
                const element = frameAnima[i];
                element.stop()
                element.play()
            }
        }
    }

    public DestroyLayerRes() {
        //临时关闭资源卸载
        if (!this.getPrefab()) {
            return;
        }

        ResManager.getInstance().destroyAssets(cc.assetManager.dependUtil.getDepsRecursively(this.getPrefab()._uuid));
        //  Utils.destroyPrefab( this.getPrefab() );
    }

    protected onDataChanged() { }

    /**
 * 点击事件
 */
    onTouchUI(e: cc.Event, switchKey: string) {

        switch (switchKey) {

            case "close":
                SceneManager.getInstance().removeLayer(this.mediator.getMediatorName());
                break;

        }
    }

}

export function _uuid(_uuid: any): string[] {
    throw new Error("Function not implemented.");
}



